package com.robot.mvvm.vm.my

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableField
import api.CommonServiceFactory
import api.UserServiceFactory
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.ToastUtils
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.PrefsManager
import com.robot.base.model.UploadFileBean
import com.robot.base.model.UserInfoBean
import com.robot.mvvm.R
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.net.URLEncoder

class PersonalInfoViewModel(application: Application) : GLBaseViewModel(application) {
    val imgUrl = ObservableField<String>()
    val userName = ObservableField<String>()
    val trueName = ObservableField<String>()
    val roleNames = ObservableField<String>()
    val departName = ObservableField<String>()
    val mobilePhone = ObservableField<String>()
    val email = ObservableField<String>()
    val type = ObservableField(false)

    val uc = UiChangeEvent()

    var avatarId = ""

    class UiChangeEvent {
        val updateAvatarEvent = SingleLiveEvent<Void>()
    }

    val updateAvatarCommand = BindingCommand<Any>(BindingAction {
        uc.updateAvatarEvent.call()
    })

    fun initData() {
        val userInfoBean = PrefsManager.getUserInfo()
        imgUrl.set(userInfoBean.avatar)
        userName.set(userInfoBean.userName)
        trueName.set(userInfoBean.trueName)
        roleNames.set(userInfoBean.roleNames)
        departName.set(userInfoBean.departName)
        mobilePhone.set(userInfoBean.mobilePhone)
        email.set(userInfoBean.email)
    }

    fun upload(
        filePath: String,
        result: (fileUrl: String?) -> Unit
    ) {
        if (TextUtils.isEmpty(filePath)) return
        val file = File(filePath)
        val requestFile =
            file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
        val part = MultipartBody.Part.createFormData(
            "file",
            URLEncoder.encode(file.name, "UTF-8"),
            requestFile
        )
        CommonServiceFactory.uploadFile(
            part, mapOf(
                "serviceType" to "avatar"
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<UploadFileBean>>(this) {
            override fun onNext(t: BaseResponse<UploadFileBean>) {
                if (t.data != null && !TextUtils.isEmpty(t.data.fileUrl)) {
                    avatarId = t.data.fileId ?: ""
                    result.invoke(t.data.fileUrl)
                }
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                LogUtils.i(e)
                result.invoke(null)
            }
        })
    }

    fun save() {
        if (TextUtils.isEmpty(trueName.get())) {
            ToastUtils.showShort(StringUtils.getString(R.string.app_error_2))
            return
        }
        showLoadingDialog()
        UserServiceFactory.updateOwnInfo(
            mapOf(
                "avatarId" to avatarId,
                "email" to email.get(),
                "mobilePhone" to mobilePhone.get(),
                "trueName" to trueName.get()
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                dismissLoadingDialog()
                getLoginUser()
            }
        })
    }

    private fun getLoginUser() {
        UserServiceFactory.getLoginUser()
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<UserInfoBean>>(this) {
                override fun onNext(t: BaseResponse<UserInfoBean>) {
                    PrefsManager.saveUserInfo(t.data)
                    initData()
                }
            })
    }
}